package com.suxii.todomvi.ui.page

import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.FloatingActionButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.viewmodel.compose.viewModel
import com.suxii.todomvi.presentation.viewmodel.TodoViewModel
import com.suxii.todomvi.presentation.intent.TodoIntent
import com.suxii.todomvi.domain.model.Todo
import com.suxii.todomvi.presentation.state.TodoDialogState
import kotlinx.coroutines.launch

@Composable
fun TodoPage(modifier: Modifier = Modifier,context: Context = LocalContext.current
,todoViewModel: TodoViewModel = viewModel()){
    // 待办状态
    val todoState by todoViewModel.todoState.collectAsState()
    // 弹窗状态
    val dialogState by todoViewModel.todoDialogState.collectAsState()
    // 作用域协程
    val scope = rememberCoroutineScope()

    // 选择列表
    var selected by remember { mutableStateOf(false) }
    val selectedItems = remember { mutableStateMapOf<Int,Boolean>() }


    Box(modifier = Modifier.fillMaxSize()){
        if(todoState.items.isNotEmpty()) {
            ShowTodoList(modifier, todoState.items, selected, selectedItems, { todo ->
                todoViewModel.showEditDialog(todo)
            }, { intent ->
                todoViewModel.invoke(intent)
            })
        }else{
            Text(text = "暂无待办，点击右下角 + 新增",
                fontWeight = FontWeight.Bold,
                fontSize = 23.sp,
                modifier = Modifier.align(Alignment.Center))
        }

        // 添加
        FloatingActionButton(onClick = {
//            Toast.makeText(context, "添加todo", Toast.LENGTH_SHORT).show()
            scope.launch {
                if (selected){
                    selected = false
                    selectedItems.clear()
                }else todoViewModel.showEditDialog(Todo(title = "", context = ""))
            }
        }
        ,modifier = Modifier
                .align(Alignment.BottomEnd)
                .padding(end = 16.dp, bottom = 50.dp)
        ) {
            Icon(imageVector = if(selected) Icons.Default.Close else Icons.Default.Add, contentDescription = "添加")
        }

        // 删除
        FloatingActionButton(onClick = {
            scope.launch {
                if (selected){
                    // 执行删除
                    /*Toast.makeText(
                        context,
                        "删除的id有 ${selectedItems.filter { e -> e.value }.keys}",
                        Toast.LENGTH_SHORT
                    ).show()*/
                    todoViewModel.invoke(
                        TodoIntent.DeleteByIds(
                        selectedItems.filter { it.value }.keys
                    ))

                    // 删除完成后清理
                    selectedItems.clear()
                    selected = false
                }else{
                    selected = true
                }
            }
        },
            containerColor = if(selected) Color.Red else FloatingActionButtonDefaults.containerColor
            ,modifier = Modifier
                .align(Alignment.BottomEnd)
                .padding(end = 16.dp, bottom = 120.dp)

        ) {
            Icon(imageVector = Icons.Default.Delete, contentDescription = "删除")
        }
    }


    // 弹窗同一处理
    when(val state = dialogState){
        is TodoDialogState.Editing -> {
            TodoDialogEdite(todo = state.todo, onConfirmation = { submit, isAdd->
                todoViewModel.invoke(if(isAdd) TodoIntent.Insert(submit) else TodoIntent.Update(submit))
                todoViewModel.dismissDialog()
            }, onDismissRequest = {
                todoViewModel.dismissDialog()
            })
        }
        TodoDialogState.Hidden -> Unit
    }


}

@Composable
fun ShowTodoList(
    modifier: Modifier = Modifier,
    items: List<Todo>,
    selected: Boolean = false,
    selectedItems: MutableMap<Int,Boolean>,
    onEditClick: (Todo) -> Unit,
    onInvoke: (TodoIntent) -> Unit
) {

    LaunchedEffect(Unit) {
        items.forEach{item-> selectedItems[item.id] = false }
    }

    LazyColumn (
        modifier = modifier
            .fillMaxSize()
            .padding(10.dp)
    ){
        items(items, key = {item-> item.id}) {
            val textColor = if (selectedItems[it.id] == true) Color.White else Color.Black
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = if (selectedItems[it.id] == true) Color.Blue else Color.Unspecified
                ),
                onClick = {
                    if(selected) {
                        selectedItems[it.id] = selectedItems[it.id] != true
                    }else{
                        onEditClick(it)
                    }
                },
                modifier = Modifier
                    .padding(8.0.dp)
//                    .clip(RoundedCornerShape(percent = 50)) // 剪切圆角
                    .fillMaxWidth()
//                    .background(if (it.id % 4 == 0) Color.Blue else Color.Unspecified)
                    ) {
                Row(
                    modifier=Modifier.padding(8.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.Top
                ) {
                    Box(modifier = Modifier.weight(1f, true)) {
                        Column(
                            modifier = Modifier.fillMaxWidth(),
                        ) {
                            Text(
                                text = it.title,
                                fontSize = 20.sp,
                                color = textColor
                            )
                            Box(modifier = Modifier.height(5.dp))
                            Text(
                                text = it.context,
                                maxLines = 3,
                                overflow = TextOverflow.Ellipsis,
                                fontSize = 16.sp,
                                color = textColor
                            )
                        }
                    }
                    Checkbox(checked = it.isDone, onCheckedChange = { value ->
                        onInvoke.invoke(TodoIntent.Update(it.copy(isDone = value)))
                    })
                }
            }
        }
    }

}

@Composable
fun TodoDialogEdite(todo: Todo,
                    onConfirmation: (Todo, Boolean) -> Unit, // 确定提交修改
                    onDismissRequest:()-> Unit, // 取消修改
                    textOk:String = "修改",
                    context: Context = LocalContext.current
){

    var todoTitle by remember { mutableStateOf(todo.title) }
    var todoContext by remember { mutableStateOf(todo.context) }
    Dialog(onDismissRequest = {/*todo 点击阴影地方触发 */}) {
        Card (
            modifier = Modifier
                .fillMaxWidth()
                .height(400.dp),
            shape = RoundedCornerShape(16.dp)
        ){
            Column(
                modifier = Modifier.padding(16.dp),
                verticalArrangement = Arrangement.Bottom
            ){

                Box(modifier = Modifier.weight(1f, fill = true)) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        // 标题
                        TextField(
                            textStyle = TextStyle(
                                color = Color.Black, fontWeight = FontWeight.Bold,
                                fontSize = 20.sp
                            ),
                            placeholder = { Text(text = "请输入标题")},
                            maxLines = 1,
                            value = todoTitle, onValueChange = {newValue->
                            todoTitle = newValue
                        })
                        TextField(
                            placeholder = {
                                Text(text = "请输入内容")
                            },
                            modifier = Modifier,
                            minLines = 20,
                            value = todoContext, onValueChange = { newValue ->
                                todoContext = newValue
                            })
                    }

                }

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    TextButton(onClick = { onDismissRequest() }) {
                        Text(text = "取消")
                    }
                    TextButton(onClick = {
                        if( todoTitle == "" || todoContext == ""){
                            Toast.makeText(context, "请输入待办标题和内容", Toast.LENGTH_SHORT).show()
                        }else onConfirmation(todo.copy(title = todoTitle, context = todoContext), todo.title == "")
                    }) {
                        Text(text = if (todo.title == "") "新增" else textOk)
                    }
                }

            }
        }
    }

}